var regexpNumber = /^(\-)?(\d)+((\.)(\d){0,2})?$/;

var DATE_FIELD_ID = 'dateFieldId';
var WEIGHT_FIELD_ID = 'weightFieldId';
var SAVE_BUTTON_ID = 'saveWeightButtonId';
var ERRORS_LIST_ID = 'errorsListId';

$(document).ready(function(){
	$('.form-button-logout').css('display', 'block');
    $('#'+DATE_FIELD_ID).attr("readOnly", true);
    
    $('#'+WEIGHT_FIELD_ID).bind('keyup blur',function(event){validate();});  
	$('.editweight-form-field-label').each(function(i, f){
		fieldLabelsMap[$('#'+f.id).attr('for')]=$('#'+f.id).text();
	});
	
	$('#'+SAVE_BUTTON_ID).click(function(event){
		validateBeforeSubmit();				
	});
	
	$('#clearButtonId').click(function(event){
		clearFields();				
	});
});

//clear alll fields and bring screen to default state
function clearFields(){
	validate();
	$('#'+WEIGHT_FIELD_ID).removeClass('form-field-valid');
	$('#'+WEIGHT_FIELD_ID).removeClass('form-field-invalid');
	$('#'+WEIGHT_FIELD_ID).val('0.0');
}

//validates all fields before submitting form to server
function validateBeforeSubmit(){
	if(validate()){
		$('#editWeightFormId').submit();
	}
}

function validate(){
	var validTotal = true;
	var validField = null;
	var errorCount = 0;
	$('#'+ERRORS_LIST_ID).empty();
	
	validField = true;
	if($('#'+WEIGHT_FIELD_ID)[0].value.length == 0){
		validField = false;
		errorCount++;
		$('#'+ERRORS_LIST_ID).append('<li>'+messages['message.error.field']+' <strong>'+fieldLabelsMap[$('#'+WEIGHT_FIELD_ID)[0].id]+'</strong> '+messages['message.error.empty']+'</li>');
	}
	//regexp test
	if(validField){
		if(!regexpNumber.test($.trim($('#'+WEIGHT_FIELD_ID)[0].value))){
			validField = false;
			errorCount++;
			$('#'+ERRORS_LIST_ID).append('<li>'+messages['message.error.field']+' <strong>'+fieldLabelsMap[$('#'+WEIGHT_FIELD_ID)[0].id]+'</strong> '+messages['message.error.field.invalid.format']+'</li>');
		}	
	}
	if(!validField){
		validTotal=false;
		$('#'+WEIGHT_FIELD_ID).removeClass('form-field-valid');
		$('#'+WEIGHT_FIELD_ID).addClass('form-field-invalid');
	}else{
		$('#'+WEIGHT_FIELD_ID).removeClass('form-field-invalid');
		$('#'+WEIGHT_FIELD_ID).addClass('form-field-valid');
	}
	
	if(!validTotal){
		var h = 100+20*errorCount;
		$('.registration-form-error-wrapper').css('height', h+'px');
		$('.registration-form-error-wrapper').css('display', 'inline-block');
		disableButton(SAVE_BUTTON_ID);
		return false;
	}else{
		$('.registration-form-error-wrapper').css('display', 'none');
		enableButton(SAVE_BUTTON_ID);
		return true;
	}
};

